// 种植系统
import { getActiveCharacter } from './character.js';
import { cropsData, gameState, ingredientsData } from './data.js';
import { cityManager } from './city.js';
import { isActiveCharacter, showAlert, showAlertByFarm, isCurrentFarm } from './utils.js';

// Crop类 - 管理单个作物数据
class Crop {
    constructor(cropTypeId, cropType) {
        this.id = `crop_${Date.now()}`;
        this.type = cropTypeId;
        this.name = cropType.name;
        this.growthDays = cropType.growthDays;
        this.growthDaysPassed = 0;
        this.harvestYield = cropType.harvestYield;
        this.plantingYear = gameState.year;
        this.plantingSeason = gameState.season;
        this.plantingDay = gameState.day;
        this.isHarvested = false;
        // 记录种植时的最优参数，用于计算产量
        this.optimalIrrigation = cropType.optimalIrrigation;
        this.optimalFertility = cropType.optimalFertility;
        this.optimalTemperature = cropType.optimalTemperature;
    }
    
    // 获取成熟度百分比
    getMaturityPercentage() {
        return Math.min((this.growthDaysPassed / this.growthDays) * 100, 100);
    }
    
    // 获取作物状态
    getStatus() {
        if (this.isHarvested) return '已收获';
        if (this.growthDaysPassed >= this.growthDays) return '可收获';
        return '生长中';
    }
    
    // 更新生长天数
    updateGrowthRate(irrigationFactor, fertilityFactor, temperatureFactor) {
        const growthRate = 1 * irrigationFactor * fertilityFactor * temperatureFactor;
        this.growthDaysPassed += growthRate;
        
        // 确保不超过总生长天数
        if (this.growthDaysPassed >= this.growthDays) {
            this.growthDaysPassed = this.growthDays;
        }
    }
    
    // 标记为已收获
    markAsHarvested() {
        this.isHarvested = true;
    }
    
    // 导出数据（用于保存）
    exportData() {
        return {
            id: this.id,
            type: this.type,
            name: this.name,
            growthDays: this.growthDays,
            growthDaysPassed: this.growthDaysPassed,
            harvestYield: this.harvestYield,
            plantingYear: this.plantingYear,
            plantingSeason: this.plantingSeason,
            plantingDay: this.plantingDay,
            isHarvested: this.isHarvested,
            optimalIrrigation: this.optimalIrrigation,
            optimalFertility: this.optimalFertility,
            optimalTemperature: this.optimalTemperature
        };
    }
}

// Farm类 - 管理农场数据
class Farm {
    constructor(city, farmData = {}) {
        this.irrigation = farmData.irrigation || 150;
        this.fertility = farmData.fertility || 50;
        this.plantedCrops = farmData.plantedCrops || [];
        this.city = city;
    }
    
    // 获取农场信息
    getFarmInfo() {
        return {
            irrigation: this.irrigation,
            fertility: this.fertility,
            plantedCrops: [...this.plantedCrops]
        };
    }
    

    // 添加种植的作物
    addPlantedCrop(crop) {
        this.plantedCrops.push(crop);
    }
    
    // 获取指定索引的作物
    getPlantedCrop(index) {
        return this.plantedCrops[index];
    }
    
    // 更新作物信息
    updatePlantedCrop(index, updates) {
        this.plantedCrops[index] = { ...this.plantedCrops[index], ...updates };
    }
    
    // 获取所有种植的作物
    getAllPlantedCrops() {
        return [...this.plantedCrops];
    }
    
    // 移除已收获的作物
    removeHarvestedCrops() {
        this.plantedCrops = this.plantedCrops.filter(crop => !crop.isHarvested);
    }
    
    // 导出数据（用于保存）
    exportData() {
        return {
            irrigation: this.irrigation,
            fertility: this.fertility,
            plantedCrops: [...this.plantedCrops]
        };
    }
    
    // 种植作物
    plantCrop(cropTypeId, character) {
        // 检查character.city和this.city是否一致
        if (character.city !== this.city) {
            return { success: false, message: '角色不在当前城市，无法操作农田' };
        }
        
        const cropType = cropsData[cropTypeId];
        
        if (!cropType) {
            return { success: false, message: '选择的作物类型不存在' };
        }
        
        // 检查灌溉和肥力是否满足最低要求
        if (this.irrigation < cropType.minIrrigation) {
            return { 
                success: false, 
                message: `灌溉值不足：需要至少 ${cropType.minIrrigation}，当前只有 ${this.irrigation}` 
            };
        }
        
        if (this.fertility < cropType.minFertility) {
            return { 
                success: false, 
                message: `肥力不足：需要至少 ${cropType.minFertility}，当前只有 ${this.fertility}` 
            };
        }
        
        const staminaCost = 20;
        if (character.stamina < staminaCost) {
            return { success: false, message: '精力不足，无法种植' };
        }
        character.stamina -= staminaCost; // 消耗玩家精力
        
        // 创建新种植的作物
        const newCrop = new Crop(cropTypeId, cropType);
        
        // 添加到农场
        this.addPlantedCrop(newCrop);
        // 提升种植技能
        increaseFarmingSkill(character, 1);
        
        return { 
            success: true, 
            crop: newCrop,
            staminaCost: staminaCost,
            message: `成功种植 ${cropType.name}！`
        };
    }
    
    // 收获作物
    harvestCrop(index, character) {
        // 检查character.city和this.city是否一致
        if (character.city !== this.city) {
            return { success: false, message: '角色不在当前城市，无法操作农田' };
        }
        
        const crop = this.getPlantedCrop(index);
        
        if (!crop || crop.isHarvested) {
            return { success: false, message: '无效的操作' };
        }
        
        if (crop.growthDaysPassed < crop.growthDays) {
            return { success: false, message: '作物尚未成熟' };
        }
        
        const staminaCost = 15;
        if (character.stamina < staminaCost) {
            return { success: false, message: '精力不足，无法收获' };
        }
        character.stamina -= staminaCost; // 消耗玩家精力
        
        // 计算产量加成
        const irrigationBonus = this.calculateIrrigationBonus(crop.optimalIrrigation, this.irrigation);
        const fertilityBonus = this.calculateFertilityBonus(crop.optimalFertility, this.fertility);
        const temperatureBonus = this.calculateTemperatureBonus(crop.optimalTemperature);
        const skillBonus = this.calculateSkillBonus(character, '耕作', '种植');
        
        // 计算最终产量
        let finalYield = crop.harvestYield * (1 + irrigationBonus) * (1 + fertilityBonus) * (1 + temperatureBonus) * (1 + skillBonus);
        finalYield = Math.round(finalYield);
        
        // 添加到玩家物品栏
        const cropName = ingredientsData[crop.type]?.name || crop.name;
        character.addItem(crop.type, finalYield, cropName, crop.description);
        
        // 标记为已收获
        this.updatePlantedCrop(index, { isHarvested: true });
        // 提升种植技能
        increaseFarmingSkill(character, 2);
        
        return { 
            success: true, 
            cropType: crop.type,
            cropName: cropName,
            yield: finalYield,
            staminaCost: staminaCost,
            message: `收获 ${cropName}，获得 ${finalYield} 个！`
        };
    }
    
    // 计算灌溉加成
    calculateIrrigationBonus(optimal, current) {
        const min = optimal * 0.8;
        const max = optimal * 1.2;
        
        if (current < min || current > max) {
            // 超出最适范围
            const distance = Math.min(
                Math.abs(current - min),
                Math.abs(current - max)
            );
            const maxDistance = optimal * 0.2;
            return -0.25 * (distance / maxDistance);
        } else {
            // 在最适范围内，计算加成
            const mid = (min + max) / 2;
            const distanceToMid = Math.abs(current - mid);
            const maxDistanceInRange = maxDistance / 2;
            return 0.25 * (1 - distanceToMid / maxDistanceInRange);
        }
    }
    
    // 计算肥力加成
    calculateFertilityBonus(optimal, current) {
        const min = optimal * 0.8;
        const max = optimal * 1.2;
        
        if (current < min || current > max) {
            // 超出最适范围
            const distance = Math.min(
                Math.abs(current - min),
                Math.abs(current - max)
            );
            const maxDistance = optimal * 0.2;
            return -0.25 * (distance / maxDistance);
        } else {
            // 在最适范围内，计算加成
            const mid = (min + max) / 2;
            const distanceToMid = Math.abs(current - mid);
            const maxDistanceInRange = maxDistance / 2;
            return 0.25 * (1 - distanceToMid / maxDistanceInRange);
        }
    }
    
    // 计算温度加成
    calculateTemperatureBonus(optimalTemperature) {
        const currentTemperature = this.city.currentTemperature;
        const min = optimalTemperature - 5;
        const max = optimalTemperature + 5;
        
        if (currentTemperature < min || currentTemperature > max) {
            // 超出最适范围
            const distance = Math.min(
                Math.abs(currentTemperature - min),
                Math.abs(currentTemperature - max)
            );
            return -0.5 * Math.min(distance / 10, 1); // 最多降低50%
        } else {
            // 在最适范围内，计算加成
            const mid = (min + max) / 2;
            const distanceToMid = Math.abs(currentTemperature - mid);
            const maxDistanceInRange = 5;
            return 0.25 * (1 - distanceToMid / maxDistanceInRange);
        }
    }
    
    // 计算技能加成
    calculateSkillBonus(character, primarySkill, secondarySkill) {
        // 使用角色实例的方法获取技能数据
        const bigSkillLevel = character.getSkillLevel(primarySkill);
        const miniSkillPoints = character.getSubSkillPoints(primarySkill, secondarySkill);
        
        const bigSkillBonus = (bigSkillLevel - 1) * 0.05; // 每级5%加成
        const miniSkillBonus = (miniSkillPoints / 100) * 0.1; // 100点小技能增加10%加成
        
        return bigSkillBonus + miniSkillBonus;
    }
    
    // 灌溉农田
    irrigateField(character) {
        // 检查character.city和this.city是否一致
        if (character.city !== this.city) {
            return { success: false, message: '角色不在当前城市，无法操作农田' };
        }
        
        const staminaCost = 15;
        if (character.stamina < staminaCost) {
            return { success: false, message: '精力不足，无法灌溉农田' };
        }
        character.stamina -= staminaCost; // 消耗玩家精力
        
        // 增加灌溉值
        const irrigationIncrease = 30;
        const newIrrigation = Math.min(300, this.irrigation + irrigationIncrease);
        const actualIncrease = newIrrigation - this.irrigation;
        
        this.irrigation = newIrrigation;
        // 提升种植技能
        increaseFarmingSkill(character, 1);
        
        return { 
            success: true, 
            staminaCost: staminaCost,
            irrigationIncrease: actualIncrease,
            newIrrigation: newIrrigation,
            message: `灌溉完成！灌溉值增加 ${actualIncrease}，当前灌溉值：${this.irrigation}`
        };
    }
    
    // 施肥农田
    fertilizeField(character) {
        // 检查character.city和this.city是否一致
        if (character.city !== this.city) {
            return { success: false, message: '角色不在当前城市，无法操作农田' };
        }
        
        const staminaCost = 18;
        if (character.stamina < staminaCost) {
            return { success: false, message: '精力不足，无法施肥农田' };
        }
        character.stamina -= staminaCost; // 消耗玩家精力
        
        // 增加肥力值
        const fertilityIncrease = 20;
        const newFertility = Math.min(100, this.fertility + fertilityIncrease);
        const actualIncrease = newFertility - this.fertility;
        
        this.fertility = newFertility;
        // 提升种植技能
        increaseFarmingSkill(character, 1);
        
        return { 
            success: true, 
            staminaCost: staminaCost,
            fertilityIncrease: actualIncrease,
            newFertility: newFertility,
            message: `施肥完成！肥力值增加 ${actualIncrease}，当前肥力值：${this.fertility}`
        };
    }
    
    // 更新灌溉值（农场自身管理）
    updateIrrigation() {
        // 基础衰减 - 根据种植作物数量每天减少灌溉值
        const cropCount = this.plantedCrops.length;
        let newIrrigation = Math.max(0, this.irrigation - (cropCount * 0.5));
        
        // 获取当前天气和季节的影响
        const weatherEffect = getWeatherIrrigationEffect(this.city.currentWeather);
        const seasonEffect = getSeasonIrrigationEffect(gameState.season);
        
        // 应用天气和季节影响
        newIrrigation = Math.max(0, Math.min(300, newIrrigation + weatherEffect + seasonEffect));
        
        // 特殊事件：夏季可能发生河流泛滥，大幅增加灌溉
        if (gameState.season === '夏季' && Math.random() < 0.05) {
            const floodAmount = Math.floor(Math.random() * 50) + 50;
            newIrrigation = Math.min(300, newIrrigation + floodAmount);
            
            // 同时增加肥力
            const newFertility = Math.min(100, this.fertility + 20);
            this.fertility = newFertility;
            
            showAlertByFarm('河流泛滥！灌溉值和肥力大幅提升！', this);
        }
        
        // 直接更新灌溉值
        this.irrigation = newIrrigation;
        
        // 刷新UI
        if (isCurrentFarm(this)) {
            updateFarmInfoDisplay();
        }
    }
    
    // 更新肥力值（农场自身管理）
    updateFertility() {
        // 基础消耗 - 根据种植作物数量调整
        const cropCount = this.plantedCrops.length;
        let fertilityChange = - (cropCount * 0.5);
        
        // 天气影响
        const weatherEffect = getWeatherFertilityEffect(this.city.currentWeather);
        fertilityChange += weatherEffect;
        
        // 更新肥力值
        this.fertility = Math.max(0, Math.min(100, this.fertility + fertilityChange));
        
        // 刷新UI
        if (isCurrentFarm(this)) {
            updateFarmInfoDisplay();
        }
    }
    
    // 更新作物生长（农场自身管理）
    updateCropGrowth() {
        // 遍历所有种植的作物
        for (const crop of this.plantedCrops) {
            // 跳过已收获的作物
            if (crop.isHarvested || crop.growthDaysPassed >= crop.growthDays) continue;
            
            // 计算灌溉因子
            const irrigationFactor = Math.min(this.irrigation / 200, 1);
            // 计算肥力因子
            const fertilityFactor = Math.min(this.fertility / 50, 1);
            // 计算温度因子
            const temperatureFactor = calculateTemperatureFactor(crop.optimalTemperature, this.city.currentTemperature);
            // 更新生长率
            crop.updateGrowthRate(irrigationFactor, fertilityFactor, temperatureFactor);
            console.log('Growth updated for crop:', crop.name);
        }
        
        // 刷新UI
        if (isCurrentFarm(this)) {
            updateFarmStatus();
        }
    }
}

// 获取当前城市的农场对象
function getCurrentFarm() {
    const currentCity = cityManager.getCurrentCity();
    return currentCity.farm;
}

// 初始化种植面板
function initFarmingPanel() {
    updateFarmInfoDisplay();
    updateFarmStatus();
    populateCropTypeSelect();
}

// 动态填充作物类型选择下拉框
function populateCropTypeSelect() {
    const cropTypeSelect = document.getElementById('cropType');
    if (!cropTypeSelect) return;
    
    // 清空现有选项
    cropTypeSelect.innerHTML = '';
    
    // 从ingredientsData中筛选出可种植的作物（类型为'谷物'的物品）
    Object.entries(ingredientsData).forEach(([ingredientId, ingredientData]) => {
        // 检查该食材是否存在对应的作物数据
        if (ingredientData.type === '谷物' && cropsData[ingredientId]) {
            const option = document.createElement('option');
            option.value = ingredientId;
            option.textContent = ingredientData.name;
            cropTypeSelect.appendChild(option);
        }
    });
}

// 更新农田信息显示
function updateFarmInfoDisplay() {
    const farm = getCurrentFarm();
    document.getElementById('irrigationValue').textContent = farm.irrigation;
    document.getElementById('fertilityValue').textContent = farm.fertility;
}

// 更新农田状态
function updateFarmStatus() {
    const farm = getCurrentFarm();
    const farmStatus = document.getElementById('farmStatus');
    farmStatus.innerHTML = '';
    
    const plantedCrops = farm.getAllPlantedCrops();
    if (plantedCrops.length === 0) {
        farmStatus.innerHTML = '<p>暂无种植作物</p>';
        return;
    }
    
    const cropTable = document.createElement('table');
    cropTable.innerHTML = `
        <thead>
            <tr>
                <th>作物名称</th>
                <th>种植日期</th>
                <th>生长天数</th>
                <th>成熟度</th>
                <th>状态</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    `;
    
    const tbody = cropTable.querySelector('tbody');
    
    plantedCrops.forEach((crop, index) => {
        console.log(crop.growthDaysPassed + ' / ' + crop.growthDays);
        // 获取成熟度和状态
        const maturityPercentage = crop.getMaturityPercentage();
        const status = crop.getStatus();
        
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${crop.name}</td>
            <td>${crop.plantingYear}年${crop.plantingSeason}第${crop.plantingDay}天</td>
            <td>${crop.growthDaysPassed}/${crop.growthDays}</td>
            <td>${Math.round(maturityPercentage)}%</td>
            <td>${status}</td>
            <td>${crop.isHarvested || maturityPercentage < 100 ? '-' : `<button onclick="harvestCrop(${index}, getActiveCharacter())">收获</button>`}</td>
        `;
        tbody.appendChild(row);
    });
    
    farmStatus.appendChild(cropTable);
}

// 种植作物
function plantCrop(character) {
    const cropTypeId = document.getElementById('cropType').value;
    const farm = character.city.farm;
    // 调用Farm类的plantCrop方法
    const result = farm.plantCrop(cropTypeId, character);
    
    if (!result.success) {
        showAlert(result.message, character);
        return;
    }
    
    // 刷新UI
    if (isActiveCharacter(character)) {
        updateFarmStatus();
        showAlert(result.message, character);
    }
}

// 收获作物
function harvestCrop(index, character) {
    const farm = character.city.farm;
    // 调用Farm类的harvestCrop方法
    const result = farm.harvestCrop(index, character);
    
    if (!result.success) {
        showAlert(result.message, character);
        return;
    }
    
    // 刷新UI
    if (isActiveCharacter(character)) {
        updateFarmStatus();
        showAlert(result.message, character);
    }
    
    // 收获完成处理已在game.js中通过cookingManager实现
}

// 增加种植技能
function increaseFarmingSkill(character, points) {
    // 技能增长逻辑
    const baseIncrease = points;
    // 使用角色实例的技能数据
    const talentBonus = character.skills['耕作'].talent * 0.1;
    const happinessFactor = character.happiness / 100;
    
    const finalIncrease = baseIncrease * (1 + talentBonus) * happinessFactor;
    
    // 使用角色实例的方法增加技能点
    const levelUpResult = character.increaseSkillPoints('耕作', '种植', finalIncrease);
    
    // 如果有升级，显示升级消息
    if (levelUpResult.leveledUp && isActiveCharacter(character)) {
        showAlert(levelUpResult.message, character);
    }
}

// 获取天气对灌溉的影响
function getWeatherIrrigationEffect(weather) {
    const effects = {
        '晴': -3,
        '多云': -2,
        '阴': -1,
        '小雨': 5,
        '大雨': 15,
        '小雪': 2,
        '大雪': 8
    };
    return effects[weather] || 0;
}

// 获取季节对灌溉的影响
function getSeasonIrrigationEffect(season) {
    const effects = {
        '春季': 1,
        '夏季': -2,
        '秋季': 0,
        '冬季': 2
    };
    return effects[season] || 0;
}

// 获取天气对肥力的影响
function getWeatherFertilityEffect(weather) {
    const effects = {
        '晴': 0,
        '多云': 0,
        '阴': 0,
        '小雨': 1,
        '大雨': 2,
        '小雪': 0,
        '大雪': 0
    };
    return effects[weather] || 0;
}

// 计算温度对生长的影响因子
function calculateTemperatureFactor(optimalTemperature, currentTemperature) {
    const minTemp = optimalTemperature - 10;
    const maxTemp = optimalTemperature + 10;
    
    if (currentTemperature < minTemp || currentTemperature > maxTemp) {
        return 0.5; // 温度不适宜，生长减慢
    } else {
        const distance = Math.abs(currentTemperature - optimalTemperature);
        return 1 - (distance / 20); // 越接近最适温度，生长越快
    }
}


// 灌溉
function irrigateField(character) {
    const farm = character.city.farm;
    const result = farm.irrigateField(character);
    
    if (result.success) {
        updateFarmInfoDisplay(); // 更新UI
        showAlert(result.message, character);
    } else {
        showAlert(result.message, character);
    }
    
    return result;
}

// 施肥
function fertilizeField(character) {
    const farm = character.city.farm;
    const result = farm.fertilizeField(character);
    
    if (result.success) {
        updateFarmInfoDisplay(); // 更新UI
        showAlert(result.message, character);
    } else {
        showAlert(result.message, character);
    }
}

// 导出函数供其他模块使用
export {
    Farm,
    initFarmingPanel,
    updateFarmInfoDisplay,
    plantCrop,
    harvestCrop,
    irrigateField,
    fertilizeField,
    updateFarmStatus,
    getCurrentFarm,
};